package com.fjc.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fjc.cache.CommonCacheUtil;
import com.fjc.dao.AUserDao;
import com.fjc.domain.AUser;
import com.fjc.domain.AUserExample;
import com.fjc.domain.ResultObject;
import com.fjc.jms.SmsProcessor;
import com.fjc.security.MD5;
import com.fjc.utils.Code;
import com.fjc.utils.UrlConnectUtil;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jms.Destination;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by fjc on 2019/2/13.
 */
@Service
public class UserService {
    @Autowired
    private AUserDao aUserDao;
    @Autowired
    private CommonCacheUtil commonCacheUtil;
    @Autowired
    private SmsProcessor smsProcessor;

    public ResultObject login(String mobile, String pwd){
        //1.去redis中查看验证码是否正确
        String value = commonCacheUtil.getCacheVale(mobile);
        if(pwd.equals(value)){
            AUserExample aUserExample = new AUserExample();
            aUserExample.createCriteria().andMobileEqualTo(mobile);
            List<AUser> userList = aUserDao.selectByExample(aUserExample);
            AUser user = null;
            if(userList.size() > 0){
                //用户存在
                user = userList.get(0);
            }else{
                //用户不存在
                user = new AUser();
                user.setMobile(mobile);
                user.setNickname(mobile);
                aUserDao.insert(user);
            }
            //生成token
            String token = MD5.MD5(mobile);
            commonCacheUtil.cacheNxExpire(token, JSONObject.toJSONString(user),3000);
            return new ResultObject(0,"登陆成功",token);
        }else{
            return new ResultObject(-1,"验证码不对");
        }
    }

    public ResultObject getMsg(String mobile)throws Exception{
        //判断缓存当中短信是否已经存在以及改手机发的次数是否超过

        //判断通过，生成验证码，存到redis,往mq发送
        String code = Code.getNonce_str();
        Destination destination = new ActiveMQQueue("sms.queue");
        JSONObject jsonObject = JSON.parseObject("{\"mobile\":\"" + mobile + "\",\"code\":\"" + code + "\"}");

        smsProcessor.sendSmsToQueue(destination,jsonObject.toJSONString());




        return new ResultObject(0,"");

    }
}
